/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   04.05.2010
 * @version SVN: $Id$
 */

package org.cakis.client.commands;

import java.rmi.RemoteException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.List;
import javax.microedition.rms.RecordStore;

import org.cakis.client.CakisMIDlet;
import org.cakis.client.forms.ProductExistForm;
import org.cakis.client.forms.ProductNotExistForm;
import org.cakis.client.forms.ScannedBarcodesForm;
import org.cakis.webservice.Product;
import org.cakis.webservice.ProductNotFoundException;
import org.cakis.webservice.StockUnitNotFoundException;

/**
 * SelectScannedProductCommand
 *
 * @author Florian Arndt
 */
public class SelectScannedProductCommand extends AbstractCommand {
	private CakisMIDlet midlet;
	private List barcodeList;
	private Product product;
	
	public SelectScannedProductCommand (CakisMIDlet m, List list) {
		super("Senden", Command.OK, 1);
		this.midlet = m;
		this.barcodeList = list;
	}
	
	public void execute() {
		String productEAN = barcodeList.getString(barcodeList.getSelectedIndex());
		
		RecordStore barcodeStore;
		try {
			barcodeStore = RecordStore.openRecordStore("barcodeStore", false);
			barcodeStore.deleteRecord(barcodeList.getSelectedIndex()+
					ScannedBarcodesForm.getRecordCount()+1);
			if (barcodeStore.getNumRecords() == 0) {
				barcodeStore.closeRecordStore();
				RecordStore.deleteRecordStore("barcodeStore");
			} else {
				barcodeStore.closeRecordStore();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ScannedBarcodesForm.setRecordCount();
		
		try {
			product = midlet.getService().getProduct(productEAN);
			ProductExistForm productExistForm = 
				new ProductExistForm(midlet, product, true);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (ProductNotFoundException pe) {
			ProductNotExistForm productNotExistForm = 
				new ProductNotExistForm(midlet, productEAN, true);
			pe.printStackTrace();
		} catch (StockUnitNotFoundException se) {
			se.printStackTrace();
		}

	}

}
